package com.example.dell.intelligentagriculture.Service;


import android.app.Service;
import android.content.Intent;
import android.os.IBinder;


import com.example.dell.intelligentagriculture.utils.Agriculture;
import com.example.dell.intelligentagriculture.utils.HttpUtil;
import com.example.dell.intelligentagriculture.utils.MyApp;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class WebService extends Service {
    private HttpUtil httpUtil;
    MyApp myApp;
    public static final String ACTION = "com.lenovo.a0424zhinengnongye.services";

    public WebService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        myApp = (MyApp) intent.getSerializableExtra("myapp");
        httpUtil=new HttpUtil();
        getDataFromServer();
        return super.onStartCommand(intent, flags, startId);
    }

    Timer  timer = new Timer();

    private void getDataFromServer() {

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    Agriculture agriculture = httpUtil.getSensor(myApp);
                    Intent intent = new Intent();
                    intent.setAction(ACTION);
                    intent.putExtra("mySensor", agriculture);
                    sendBroadcast(intent);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, 1000, 10000);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
